import { Button, Form, Modal, Tooltip, Input } from "antd";
import { useForm } from "antd/es/form/Form";
import { FormInstance } from "rc-field-form";
import React, { useEffect, useRef, useState } from "react";

const { TextArea } = Input;

const jsonTemplate = `{
"tableName": "test_table",
"tableComment":"测试表格",
"fieldList": [
    {
        "fieldName": "username",
        "mockType": "username",
        "comment": "用户名",
        "fieldType": "varchar",
        "javaOptions": "['swagger', 'mybatis']",
        "options": "['isNull']"
    },
    {
        "fieldName": "sex",
        "mockType": "sex",
        "comment": "性别",
        "fieldType": "varchar"
    }
]
}`

const OptionImport: React.FC<{ onConfirm: (value: string) => void }> = (props) => {

    const formRef = useRef<any>(null);

    const [visible, setVisible] = useState(false);

    function handleOk() {
        const ref = formRef.current as FormInstance;
        ref.validateFields().then(res => {
            props.onConfirm(ref.getFieldValue('jsonCode'));
            onClose();
        });
    }

    function onClose() {
        (formRef.current as FormInstance).setFieldValue('jsonCode', '');
        setVisible(false);
    }

    function handleSetTemplate() {
        (formRef.current as FormInstance).setFieldValue('jsonCode', jsonTemplate);
    }

    return <div style={{ marginLeft: '12px' }}>
        <Tooltip title="输入配置，完成导入">
            <Button onClick={() => setVisible(true)} type="primary">导入配置</Button>
        </Tooltip>
        <Modal onCancel={onClose} onOk={handleOk} open={visible} title="导入配置">
            <div style={{ marginBottom: '24px' }}>
                <span style={{ color: 'red' }}>*</span> 请输入表结构 JSON： <Button onClick={handleSetTemplate}>导入示例</Button>
            </div>
            <Form ref={formRef}>
                <Form.Item name="jsonCode" rules={[{ required: true, message: '请输入配置' }]}>
                    <TextArea placeholder="输入 json 配置" style={{ height: '400px' }}></TextArea>
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default OptionImport;
